package com.eii.excel.util;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class DownloadUtil {

    public static void setDownloadProp(HttpServletResponse response){
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Access-Control-Expose-Headers", "filename");
    }

    public static void writeStream(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String filename) throws IOException {
        setDownloadProp(response);
        response.addHeader("filename", URLEncoder.encode(filename, "UTF-8"));
        response.setContentLength(byteArrayOutputStream.size());
        ServletOutputStream outputstream = response.getOutputStream();	//取得输出流
        byteArrayOutputStream.writeTo(outputstream);					//写到输出流
        byteArrayOutputStream.close();									//关闭
        outputstream.flush();											//刷数据
    }

    public static void writeStream(byte[] data, HttpServletResponse response, String filename) throws IOException {
        setDownloadProp(response);
        response.addHeader("filename", URLEncoder.encode(filename, "UTF-8"));
        response.setContentLength(data.length);
        ServletOutputStream outputstream = response.getOutputStream();	//取得输出流
        outputstream.write(data);					//写到输出流
        outputstream.flush();											//刷数据
    }

    public static void setDownloadProp(HttpServletResponse response,String filename) throws UnsupportedEncodingException {
        setDownloadProp(response);
        response.addHeader("filename", URLEncoder.encode(filename, "UTF-8"));
    }
}
